import cv2
import os
import glob
import numpy as np

def frames_to_video(frame_dir, output_path, fps=30, bg_color=(255, 255, 255)):
    """
    将路径下的帧序列合成为视频，支持透明通道，透明部分用指定颜色填充。

    Args:
        frame_dir (str): 帧序列文件夹路径
        output_path (str): 输出视频路径 (如 output.mp4)
        fps (int): 帧率，默认 30
        bg_color (tuple): 背景颜色 (B, G, R)，默认白色
    """
    # 按文件名排序读取 (0000.png, 0001.png, ...)
    frame_files = sorted(glob.glob(os.path.join(frame_dir, "*.png")))
    if not frame_files:
        raise ValueError(f"在 {frame_dir} 下没有找到帧文件！")

    # 读取第一帧获取尺寸
    first_frame = cv2.imread(frame_files[0], cv2.IMREAD_UNCHANGED)  # 读 RGBA
    height, width = first_frame.shape[:2]

    # 定义视频编码器和输出
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

    for f in frame_files:
        frame = cv2.imread(f, cv2.IMREAD_UNCHANGED)  # 可能是 BGRA
        if frame.shape[2] == 4:  # 处理透明通道
            bgr = frame[:, :, :3]
            alpha = frame[:, :, 3:] / 255.0  # 归一化 alpha
            bg = np.full_like(bgr, bg_color, dtype=np.uint8)
            frame = (alpha * bgr + (1 - alpha) * bg).astype(np.uint8)
        out.write(frame)

    out.release()
    print(f"视频已保存到: {output_path}")


path = "pose_gyj_1"
for i in range(6):
    image_path = os.path.join(path, f"{i}","com")
    save_path = os.path.join(path, f"{i}.mp4")
    frames_to_video(image_path, save_path)
